package com.easy.sso.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.easy.common.exception.ExceptionEnum;
import com.easy.common.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * @Author: CoolPro
 * @Description:
 * @Time: 2024-04-23 14:27
 **/
@Component
public class JwtUtil {
    @Value("${secret}")
    private static final String secret = "easy.com";
    @Value("${outTime}")
    private static final Integer outTime = 30 * 1000;

    public static String generateToken(String account) {
        Date date = new Date(System.currentTimeMillis() + outTime);
        //获取校验器
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withHeader(new HashMap<>())
                .withClaim("ac", account)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static Result verify(String token) {
        try {
            //根据密码生成校验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier ac = JWT.require(algorithm).build();
            ac.verify(token);
            return Result.success();
        } catch (TokenExpiredException e) {
            return Result.error(ExceptionEnum.JWT_OUT_TIME);
        } catch (Exception e) {
            return Result.error(ExceptionEnum.JWT_FAIL);
        }
    }
}
